<?php

namespace Frieza\Modules\Activity\Controllers;

use Biz\service\activity\ServeActivityArchive;
use Biz\service\advertisement\spotlight\SpotlightActivityService;
use Encore\Admin\Widgets\Table;
use Illuminate\Contracts\Support\Renderable;

class SpotlightCache implements Renderable
{
    public function render($key = null)
    {
        $activity = SpotlightActivityService::getActivity($key);
        $archive = ServeActivityArchive::getInstance()->getArchive(ServeActivityArchive::SPOTLIGHT_ACTIVITY_ID, $key);
        if ($archive) {
            $allSubscribeData = $archive['subscribe'];
            $allNextSubscribeData = $archive['nextSubscribe'];
            $allOpenData = $archive['open'];
            $allGuessData = $archive['guess'];
            $allFeaturesData = $archive['features'];
        } else {
            $allSubscribeData = $activity->allSubscribe();
            $allNextSubscribeData = $activity->allNextSubscribe();
            $allOpenData = $activity->allOpen();
            $allGuessData = [];
            $allFeaturesData = [];
        }
        $allSubscribe = $this->formatSingleNick($allSubscribeData, '预约页一键预约');
        $allNextSubscribe = $this->formatSingleNick($allNextSubscribeData, '预定下次幸运');
        $allOpen = $this->formatSingleNick($allOpenData, '发布页打开盒子');
        $allGuess = $this->formatGuess($activity->showAllGuess($allGuessData), '新品猜一猜');
        $allFeatures = $this->formatGuess($activity->showAllLikeFeatures($allFeaturesData), '新品打call');
        $response = array_merge($allOpen, $allSubscribe, $allGuess, $allFeatures, $allNextSubscribe);
        return implode("<br/>", $response);
    }

    public function formatGuess($all, $title): array
    {
        $nick = $this->getNick(array_keys($all));
        $arr = [];
        foreach ($all as $uid => $v) {
            $arr[] = [$uid, $nick[$uid] ?? '-', $v ? implode(',', $v) : '-'];
        }
        return [
            (new Table(["$title 用户id (". count($arr) .")", '昵称', '选项'], $arr))->render(),
        ];
    }

    public function formatSingleNick($all, $title): array
    {
        $all = $this->getNick($all);
        $arr = [];
        foreach ($all as $uid => $nick) {
            $arr[] = [$uid, $nick];
        }
        return [
            (new Table(["$title 用户id (". count($arr) .")", '昵称'], $arr))->render(),
        ];
    }

    public function getNick($uids): array
    {
        $userInfo = empty($uids) ? [] : \Doraemon\model\Member::getUserInfoByIds($uids);
        return array_column($userInfo, 'nick', 'uid');
    }
}